package com.hethongviet.preventingmachine.page;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hethongviet.preventingmachine.AppMain;
import com.hethongviet.preventingmachine.Config;
import com.hethongviet.preventingmachine.Constants;
import com.hethongviet.preventingmachine.R;
import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.helps.OnSMSMessageFailListener;
import com.hethongviet.preventingmachine.helps.OnSMSMessageListener;
import com.hethongviet.preventingmachine.helps.SMSHelper;
import com.hethongviet.preventingmachine.helps.SmsReceiverDefault;
import com.hethongviet.preventingmachine.helps.db.AccountSQLite;
import com.hethongviet.preventingmachine.helps.dialog.DialogMessageBack;
import com.hethongviet.preventingmachine.models.SMS;
import com.hethongviet.preventingmachine.models.Transaction;
import com.hethongviet.preventingmachine.models.Account;

public class PageChangePasswordActivity extends Activity implements
		OnSMSMessageListener, OnSMSMessageFailListener
{
	private String _newPassword = null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		Utils.prepareWindow(this);

		SMSHelper.setActivity(this);

		setContentView(R.layout.page_change_password);

		final String oldPassword = getIntent().getStringExtra(
				Constants.EXTRA_PASSWORD);

		final EditText editTextOldPassword = (EditText) findViewById(R.id.change_password_edit_old_password);
		final EditText editTextNewPassword = (EditText) findViewById(R.id.change_password_edit_new_password);
		final EditText editTextReinputPassword = (EditText) findViewById(R.id.change_password_edit_reinput_password);

		final Button buttonAccept = (Button) findViewById(R.id.change_button_accept);
		final Button buttonCancel = (Button) findViewById(R.id.change_button_cancel);

		buttonAccept.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				String oldPasswordReinput = editTextOldPassword.getText().toString();
				if (oldPasswordReinput == null
						|| !oldPasswordReinput.equals(oldPassword))
				{
					showDialogWithCatch(R.string.message_error_input_password_old_not_correct);
					return;
				}

				for (int index = 0; index < oldPasswordReinput.length(); index++)
				{
					char c = oldPasswordReinput.charAt(index);

					if (!Character.isLetterOrDigit(c))
					{
						showDialogWithCatch(R.string.message_error_wrong_input_password);
						return;
					}
				}

				_newPassword = editTextNewPassword.getText().toString();
				if (_newPassword == null || _newPassword.equals(""))
				{
					editTextNewPassword.setText("");
					showDialogWithCatch(R.string.message_error_input_null);
					return;
				}

				for (int index = 0; index < _newPassword.length(); index++)
				{
					char c = _newPassword.charAt(index);

					if (!Character.isLetterOrDigit(c))
					{
						showDialogWithCatch(R.string.message_error_wrong_input_password);
						return;
					}
				}

				if (_newPassword.length() < Constants.LENGTH_MIN_NAME)
				{
					showDialogWithCatch(R.string.message_error_input_too_short_password);
					return;
				}

				if (_newPassword.length() > Constants.LENGTH_MAX_NAME)
				{
					showDialogWithCatch(R.string.message_error_input_too_long_password);
					return;
				}

				if (_newPassword.equals(oldPassword))
				{
					showDialogWithCatch(R.string.message_error_input_password_same_old);
					return;
				}

				String reinputPassword = editTextReinputPassword.getText().toString();
				if (reinputPassword == null
						|| !reinputPassword.equals(_newPassword))
				{
					showDialog(R.string.message_error_input_password_reinput_not_same);
					return;
				}

				/* Send SMS change user_name */
				Utils.showProgress(PageChangePasswordActivity.this);

				SMSHelper.changePassword(_newPassword,
						R.string.message_fail_change_password);
				debugSendSMS(SMSHelper.DEBUG_SMS_CHANGE_PASSWORD);
			}
		});
		buttonCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

	private void debugSendSMS(final String message)
	{
		final SMS sms = new SMS();
		sms.setRecipient(SMSHelper.getDeviceNumber());
		sms.setMessage(message);

		if (Config.IS_DEBUG_SMS_RECEIVE)
		{
			new Thread(new Runnable() {

				@Override
				public void run()
				{
					try
					{
						Thread.sleep(Constants.TIME_DEBUG_SEND_SMS);
					} catch (Exception e)
					{
						e.printStackTrace();
					}
					PageChangePasswordActivity.this.runOnUiThread(new Runnable() {

						@Override
						public void run()
						{
							onSMSMessageIncoming(sms);
						}
					});
				}
			}).start();

		}
	}

	@Override
	public void onSMSMessageIncoming(SMS sms)
	{

		String message = Utils.prepareMessage(sms.getMessage());
		Utils.debug("Message receive = " + message);

		Transaction transaction = SMSHelper.solve(message);
		if (transaction != null)
		{
			String codeSMS = transaction.getCodeSend();
			Utils.debug("codeSMS = " + codeSMS);

			String contentSMS = transaction.getMessageReceive();
			Utils.debug("contentSMS = " + contentSMS);

			if (codeSMS.equals(SMSHelper.CODE_CHANGE_PASSWORD))
			{
				if (contentSMS.contains(SMSHelper.CODE_OK))
				{
					setResult(RESULT_OK);

					AccountSQLite accountSQLite = new AccountSQLite(this, AppMain.getInstance().getDBName());
					Account account = accountSQLite.getAll().get(0);
					account.setPassword(_newPassword);
					accountSQLite.insert(account);

					SMSHelper.setPassword(_newPassword);

					showDialogWithCatch(R.string.message_success_change_password);
				}
				else
				{
					setResult(RESULT_CANCELED);
					showDialogWithCatch(R.string.message_error_change_password_fail);
				}
			}

			Utils.hideProgressDialog();
		}
	}

	@Override
	protected void onResume()
	{

		SmsReceiverDefault.setOnSMSMessageListener(this);
		SMSHelper.setActivity(this);
		SMSHelper.setMessageId(0);
		
		super.onResume();
	}
	
	private void showDialogWithCatch(int id)
	{
		try
		{
			showDialog(id);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_error_change_password_fail)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_success_change_password)
		{
			return new DialogMessageBack(this, false, id, true);
		}
		else if (id == R.string.message_error_input_too_long_password)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MAX_PASSWORD), false);
		}
		else if (id == R.string.message_error_input_too_short_password)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MIN_PASSWORD), false);
		}
		else return new DialogMessageBack(this, true, id, false);
	}

	@Override
	public void onSMSMessageFail(final Transaction transaction, final int messageFailId)
	{
		runOnUiThread(new Runnable() {

			@Override
			public void run()
			{
				if (messageFailId > 0) Toast.makeText(
						PageChangePasswordActivity.this, messageFailId,
						Toast.LENGTH_LONG).show();

				if (messageFailId == R.string.message_fail_change_password)
				{
					Utils.hideProgressDialog();
				}
			}
		});

	}
}
